package cn.sdormitory.mq;


import cn.sdormitory.smartdor.service.SdAttenceService;
import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @className: AttenceRecordsPushListener
 * @author: Alex
 * @date: 2023/9/28
 **/
@Component
@Slf4j
public class AttenceRecordsPushListener {

//	@Resource
//	private AccessRecordUtils accessRecordUtils;

	@Autowired
	private SdAttenceService sdAttenceService;


	@RabbitListener(bindings = @QueueBinding(
			value = @Queue(value = "iot-attendance-records-push", durable = "true"),
			exchange = @Exchange(name = "iot-device-prod",
					durable = "true",
					type = "topic",
					ignoreDeclarationExceptions = "true"),
			key = "iot.attendance.records.push"
	), ackMode = "MANUAL"
	)


	@RabbitHandler
	public void onMessage(Message message, Channel channel) throws Exception {
		//	1. 收到消息以后进行业务端消费处理
		System.err.println("-----------------------");
		System.err.println("消费消息:" + message.getPayload());

		String messageStr = String.valueOf(message.getPayload());
		Map<String, String> map = JSON.parseObject(messageStr, Map.class);

		List<Map<String, String>> list = new ArrayList<>();
		list.add(map);

		sdAttenceService.receiveSdAttendanceRecords(list);

		String type = (String) map.get("type");
		//处理成功之后 获取deliveryTag 并进行手工的ACK操作, 因为我们配置文件里配置的是 手工签收
		Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
		channel.basicAck(deliveryTag, true);
		System.err.println("消息已手工签收");
	}

//	private void pushDormitoryRecords(Map<String, Object> map) {
//		String startTime = Objects.toString(map.get("beginTime"));
//		String endTime = Objects.toString(map.get("endTime"));
//
//		String iotDeviceId = Objects.toString(map.get("deviceNo"));
//		// 查询出设备信息
//		IotDeviceDao iotDeviceDao = SpringUtils.getBean("iotDeviceDao");
//		LambdaQueryWrapper<IotDeviceVO> queryWrapper = new LambdaQueryWrapper<>();
//		queryWrapper.eq(IotDeviceVO::getDeviceCode, iotDeviceId);
//		IotDeviceVO deviceVO = iotDeviceDao.selectOne(queryWrapper);
//
//		try {
//			Result<List<AccessRecord>> records = accessRecordUtils.findRecordsByDevice(deviceVO, null, startTime, endTime);
//
//			List<AccessRecord> result = records.getResult();
//			if (CollectionUtil.isEmpty(result)) {
//				log.info("在{} ~ {} 时间段,没有查询出考勤数据", startTime, endTime);
//				return;
//			}
//			result = result.stream().filter(item -> item.getBStatus() == 1).collect(Collectors.toList());
//			// 推送数据
//			List<AccessRecordVo> accessRecordVos = new ArrayList<>();
//			for (AccessRecord accessRecord : result) {
//				AccessRecordVo accessRecordVo = new AccessRecordVo();
//				BeanUtils.copyProperties(accessRecord, accessRecordVo);
//				accessRecordVo.setStuTime(DateUtils.formatTimezoneAdd8Hour(accessRecordVo.getStuTime()));
//				accessRecordVo.setDeviceLocation(String.valueOf(deviceVO.getBsloId()));
//				accessRecordVo.setDeviId(deviceVO.getId());
//				accessRecordVo.setDeviceCode(deviceVO.getDeviceCode());
//				accessRecordVo.setDeviceName(deviceVO.getDeviceName());
//				accessRecordVo.setDeviceIp(deviceVO.getDeviIp());
//				accessRecordVo.setAttenceLocation(deviceVO.getAttenceLocation());
//				accessRecordVos.add(accessRecordVo);
//			}
//			AttendanceDeviceService attendanceDeviceService = SpringUtils.getBean(AttendanceDeviceService.class);
//			log.info("开始推送考勤数据至宿管系统: {}, 总共：{}条", DateUtil.formatDateTime(new Date()), accessRecordVos.size());
//			attendanceDeviceService.syncDormitoryAttendanceRecords(accessRecordVos);
//		} catch (UnsupportedEncodingException e) {
//			log.error("查询考勤设备流水信息失败！");
//		}
//	}
}
